<?php
namespace app\company\controller;
use app\AdminRest;
use app\banquet\info\PermissionBanquet;
use app\card\model\UserInfo;
use app\dynamic\model\CardCompany;
use think\App;
use app\company\model\CardCompany as CompanyModel;
use app\card\model\CardJob as JobModel;
use longbingcore\tools\LongbingArr;
/**
 * @model company
 * @author yangqi
 * @create time 2019年11月26日16:22:05
 */
class Admin extends AdminRest
{
    public function __construct(App $app) {
        parent::__construct($app);
    }

    //获取公司列表
    public function listCompany() {
//      var_dump(json_encode(longbingInitRadarMessage() ,true));die;
//      var_dump(longbingGetPersionalCenterMenu());die;
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取公司列表数据
        $result = longbingGetAllCompany($uniacid);
        //返回数据
        return $this->success($result);
    }

    //获取公司信息
    public function getCompany() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取公司id
        $company_id = null;
        //检查公司id是否存在
        if(isset($this->_param['id']) && !empty($this->_param['id'])) $company_id = $this->_param['id'];
        if(empty($company_id)) return $this->success([]);
        //生成查询条件
        $filter = [
            ['uniacid', '=', $uniacid],
            ['status', '>', -1],
            ['id', '=', $company_id]
        ];
        //生成公司模型
        $company_model = new CompanyModel();
        //获取公司数据
        $result = $company_model->getCompany($filter);
        //服务标签
        $result['service_tag'] = !empty($result['service_tag'])?explode(',',$result['service_tag']):[];

        return $this->success($result);
    }


    /**
     * @Purpose: 下架 / 上架 / 删除公司
     *
     * @Method: POST
     *
     * @Param：$company_id   number  公司id
     * @Param：$method   number  操作类型  0 = 下架 1 = 上架 2 = 删除
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function company_change()
    {
        $verify = ['company_id' => 'required', 'method' => 0];

        $params = lbGetParamVerify($this->_input, $verify);
        $company = new CardCompany();
        //检查公司下是否有员工
        if($this->_input['status'] == 0 ){
            $count = longbingGetStaffCount($params['company_id']);
            if(!empty($count)) return $this->error(lang('have staff in company company_change'));
        }

        $result = $company->updateStatus($params['company_id'], $this->_input['status']);
        if ($result === false) {
            return $this->error('operation failed');
        }
        return $this->success([]);
    }

    //更新公司信息
    public function updateCompany() {

        //获取uniacid
        $uniacid = $this->_uniacid;

        $company_id = null;
        //检查公司id是否存在
        if(isset($this->_param['company_id']) && !empty($this->_param['company_id'])) $company_id = $this->_param['company_id'];

//        dump($this->_param);exit;

        if(empty($company_id)) return $this->error(lang('company not exist'));
        //获取当前公司是否存在
        $company = longbingGetUserCompany($company_id ,$uniacid);
        if(empty($company)) return $this->error(lang('company not exist'));
        //获取公司数据
        $input   = $this->_input;


        if(isset($input['status']))
        {
            $status = 0;

            if(!empty($input['status'])) $status = 1;

            $input['status'] = $status;
        }

        if(isset($input['data'])) $input = $input['data'];
        //生成公司模型
        $company_model = new companyModel();
        if(isset($input['name']) && !in_array($input['name'], [$company['name']])){
            //检查数据是否存在
            $where = [
                ['name','=',$input['name']],
                ['status','<>',-1],
                ['pid','=',0],
                ['uniacid','=',$uniacid]
            ];
            $count = $company_model->getCompanyCount($where);
            if(!empty($count)) return $this->error(lang('company is exist'));
        }
        //判断官网轮播图是否存在（转化成字符串存储）
        if (!empty($input['culture'])) {
            $input['culture'] = trim(implode(',', $input['culture']), ',');
        }
        //服务标签
        if (!empty($input['service_tag'])) {

            $input['service_tag'] = trim(implode(',', $input['service_tag']));
        }


        $input['uniacid'] = $uniacid;
//      var_dump(['id' => $company_id ,'uniacid' => $uniacid]);die;
        if(!empty($input['name'])&&strlen($input['name'])>50){
            return $this->error('公司名称过长');
        }

        $result = $company_model->updateCompany(['id' => $company_id ,'uniacid' => $uniacid] ,$input);
        //同步下级排序值
        if(isset($input['top'])){

            $company_model->where(['pid'=>$company_id])->update(['top'=>$input['top']]);
        }
        //By.jingshuixian 当修改顶级公司时,要修改子部门的联系方式

        if($result){
            //获取所有子公司ID信息
            $companyIdList = array_unique($company_model->getCompanyUser_l($company_id));

            $sonAddress = LongbingArr::delBykey( $input , ['top','short_name','name'] ) ;

            foreach ($companyIdList as $company_id ){

                $company_model->updateCompany(['id' => $company_id ,'uniacid' => $uniacid] ,$sonAddress);
                //刷新缓存
                longbingGetUserCompany($company_id ,$uniacid ,true ) ;

            }

        }


        //刷新缓存
        longbingGetUserCompany($company_id ,$uniacid ,true);
        //清理缓存 By.jingshuixian
        clearCache($this->_uniacid);
        return $this->success($result);
    }

    //创建公司
    public function createCompany() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取公司id
        $input   = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        //生成公司模型
        $company = new companyModel();

        if(!empty($input['name'])&&strlen($input['name'])>50){
            return $this->error('公司名称过长');
        }
        //检查数据是否存在
        $where = [
            ['name','=',$input['name']],
            ['status','<>',-1],
            ['pid','=',0],
            ['uniacid','=',$uniacid]
        ];
        $count = $company->getCompanyCount($where);

        if(!empty($count)) return $this->error(lang('company is exist'));
        //判断官网轮播图是否存在（转化成字符串存储）
        if (!empty($input['culture'])) {
            $input['culture'] = trim(implode(',', $input['culture']), ',');
        }
        //服务标签
        if (!empty($input['service_tag'])) {

            $input['service_tag'] = trim(implode(',', $input['service_tag']));
        }

        $input['uniacid'] = $uniacid;
        $result = $company->createCompany($input);
        return $this->success($result);
    }
    //删除公司
    public function delCompany() {
        //获取uniacid
        $uniacid    = $this->_uniacid;
        //获取公司id
        $company_id = null;
        //检查公司id是否存在
        if(isset($this->_param['company_id']) && !empty($this->_param['company_id'])) $company_id = $this->_param['company_id'];
        if(empty($company_id)) return $this->error(lang('company not exist'));
        //检查公司下是否有下级部门
        $count = longbingGetSonCompanyCount($company_id);
        if(!empty($count)) return $this->error(lang('have next department'));
        //检查公司下是否有员工
        $count = longbingGetStaffCount($company_id);
        if(!empty($count)) return $this->error(lang('have staff in company'));
        //生成公司操作模型
        $company_model = new companyModel();
        //删除
        $result     = $company_model->delCompany([['uniacid' ,'=' ,$uniacid ] ,['id' , '=', $company_id] ,['status' ,'>' ,-1]]);
        //刷新缓存
        longbingGetUserCompany($company_id ,$uniacid ,true);
        //返回数据
        return $this->success($result);
    }

    //创建部门
    public function createDepartment(){
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取参数
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        $company_id = $input['pid'];
        //获取公司信息
        $company    = longbingGetUserCompany($company_id ,$uniacid);
        //判断公司是否存在
        if(empty($company)) return $this->error(lang('company not exist'));
        //处理数据
        $company['name'] = $input['name'];
        $company['pid']  = $company_id;
        $company['create_time'] = time();
        $company['update_time'] = time();
        $company['status'] = 1;
        if(empty($company['top_id'])) $company['top_id'] = $company_id;
        $company['uniacid'] = $uniacid;
        unset($company['id']);
        //创建部门
        $company_model = new CompanyModel();
        $result = $company_model->createCompany($company);
        return $this->success($result);
    }

    //获取部门信息
    public function getDepartment() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取部门id
//      $department_id = $this->_param['department_id'];
        $department_id = null;
        //检查公司id是否存在
        if(isset($this->_param['department_id']) && !empty($this->_param['department_id'])) $department_id = $this->_param['department_id'];
//      if(empty($department_id)) return $this->error(lang('department not is exist'));
        if(empty($department_id)) return $this->success([]);
        $result = longbingGetUserCompany($department_id ,$uniacid);
        return $this->success($result);
    }


    /**
     * 上下架部门
     *
     * @return \think\Response
     * @author shuixian
     * @DataTime: 2019/12/18 16:15
     */
    public function department_change(){
        //检查公司id是否存在
        if (isset($this->_input['department_id']) && !empty($this->_input['department_id'])) $department_id = $this->_input['department_id'];
        if (empty($department_id)) return $this->error(lang('department not is exist'));
        //检查公司下是否有员工
        if($this->_input['status'] == 0 ) {
            //检查是否有员工
            $count = longbingGetStaffCount($department_id);
            if(!empty($count)) return $this->error(lang('have staff in department department_change'));
        }

        //生成操作模型
        $company_model = new CompanyModel();
        $result = $company_model->updateCompany(  [ ['status' ,'>' , -1 ] , ['id' , '=', $department_id] ] ,[ 'status' => $this->_input['status'] ]  );
        //刷新缓存
        longbingGetUserCompany($department_id ,$this->_uniacid ,true);
        //返回数据
        return $this->success($result);

    }

    public function updateDepartment() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取部门id
//      $department_id = $this->_param['department_id'];
        $department_id = null;
        //检查公司id是否存在
        if(isset($this->_param['department_id']) && !empty($this->_param['department_id'])) $department_id = $this->_param['department_id'];
        if(empty($department_id)) return $this->error(lang('department not is exist'));
        //获取部门数据
        $department = longbingGetUserCompany($department_id ,$uniacid);
        if(empty($department)) return $this->error(lang('department not is exist'));
        //获取修改数据
        $input = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        if(isset($input['status']))
        {
            $status = 1;
            if(empty($input['status'])) $status = 0;
            $input['status'] = $input['status'];
        }
        //生成操作模型
        $company_model = new CompanyModel();
        $result = $company_model->updateCompany(['id' => $department_id] ,$input);
        //刷新缓存
        longbingGetUserCompany($department_id ,$uniacid ,true);
        //返回数据
        return $this->success($result);
    }

    //修改部门信息
    public function delDepartment() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取部门id
//      $department_id = $this->_param['department_id'];
        $department_id = null;
        //检查公司id是否存在
        if(isset($this->_param['department_id']) && !empty($this->_param['department_id'])) $department_id = $this->_param['department_id'];
        if(empty($department_id)) return $this->error(lang('department not is exist'));
        //获取部门数据
        $department = longbingGetUserCompany($department_id ,$uniacid);
        if(empty($department)) return $this->error(lang('department not is exist'));
        //判断是否有子部门存在
        $company_model = new CompanyModel();
        $count         = $company_model->getCompanyCount([['pid' ,'=' , $department_id] ,['status' , '>' ,-1]]);
        if(!empty($count)) return $this->error(lang('have next department'));
        //检查是否有员工
        $count = longbingGetStaffCount($department_id);
        if(!empty($count)) return $this->error(lang('have staff in department'));
        //删除数据
        $company_model = new CompanyModel();
        $result        = $company_model->delCompany([['uniacid' ,'=' ,$uniacid ] ,['id' , '=', $department_id] ,['status' ,'>' ,-1]]);
        longbingGetUserCompany($department_id ,$uniacid ,true);

        return $this->success($result);
    }

    //获取职位详情
    public function getJob() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取job id
//      $job_id = $this->_param['job_id'];
        $job_id = null;
        //检查职位是否存在
        if(isset($this->_param['job_id']) && !empty($this->_param['job_id'])) $job_id = $this->_param['job_id'];
//      if(empty($job_id)) return $this->error(lang('job not exist'));
        if(empty($job_id)) return $this->success([]);
        //生成工作操作类
        $result    = longbingGetJob($job_id ,$uniacid);
        return $this->success($result);
    }
    //获取职位列表
    public function listJob() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取查询参数
        $param   = $this->_param;
        //生成职位模型
        $job_model = new JobModel();
        //配置查询参数
        $filter = [['uniacid' ,'=' ,$uniacid] ,['status' ,'>' , -1]];
        if(isset($param['keyword'])) $filter[] = ['name' ,'like' ,'%' . $param['keyword'] . '%'];
        //初始化分页数据
        $page_config = array(
            'page' => 1,
            'page_count' => 10
        );
        //获取分页信息
        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        //获取总数
        $page_config['total'] = $job_model->getJobCount($filter);
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        $result  = $page_config;
        if(empty($result['total'])) {
            $result['data'] = [];
            return $this->success($result);
        }
        //获取数据
        $result['data'] = $job_model->listJob($filter ,$page_config);
        return $this->success($result);
    }
    //创建职位
    public function createJob() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取职位信息
        $input  = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        $input['uniacid'] = $uniacid;
        //创建
        $job_model = new JobModel();
        $result    = $job_model->createJob($input);
        return $this->success($result);
    }
    //修改职位
    public function updateJob() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取job id
//      $job_id = $this->_param['job_id'];
        $job_id = null;
        //检查职位是否存在
        if(isset($this->_param['job_id']) && !empty($this->_param['job_id'])) $job_id = $this->_param['job_id'];
        if(empty($job_id)) return $this->error(lang('job not exist'));
        //检查是否存在
        $job    = longbingGetJob($job_id ,$uniacid);
        if(empty($job)) return $this->error(lang('not job'));
        //获取修改信息
        $input  = $this->_input;
        if(isset($input['data'])) $input = $input['data'];
        if(isset($input['status']))
        {
            $status = 1;
            if(empty($input['status'])) $status = 0;
            $input['status'] = $input['status'];
        }
        //修改数据
        $job_model = new JobModel();
        $result = $job_model->updateJob(['id' => $job_id] ,$input);
        //刷新缓存
        longbingGetJob($job_id ,$uniacid ,true);
        //返回数据
        return $this->success($result);
    }
    //删除职位
    public function delJob() {
        //获取uniacid
        $uniacid = $this->_uniacid;
        //获取job id
//      $job_id = $this->_param['job_id'];
        $job_id = null;
        //检查职位是否存在
        if(isset($this->_param['job_id']) && !empty($this->_param['job_id'])) $job_id = $this->_param['job_id'];
        if(empty($job_id)) return $this->error(lang('job not exist'));
        //检查是否存在
        $job    = longbingGetJob($job_id ,$uniacid);
        if(empty($job)) return $this->error(lang('not job'));
        //删除
        $job_model = new JobModel();
        $result = $job_model->delJob(['id' => $job_id ,'uniacid' => $uniacid]);
        //刷新缓存
        longbingGetJob($job_id ,$uniacid ,true);
        //返回数据
        return $this->success($result);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-11 15:45
     * @功能说明:获取插件权限
     */
    public function getPlugAuth(){

        $p_banquet = new PermissionBanquet($this->_uniacid);
        //宴会厅插件权限
        $data['banquet_auth'] = $p_banquet->pAuth();

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-15 16:26
     * @功能说明:获取指定公司下面的员工
     */
    public function getCompanyStaff(){

        $input = $this->_param;

        $dis = [

            'is_staff'   => 1,

            'company_id' => $input['company_id']
        ];

        $user_info_model = new UserInfo();

        $data = $user_info_model->where($dis)->field('fans_id,name')->select()->toArray();

        if(!empty($data)){

            foreach ($data as &$v){

                $v['name'] = lbUserName($v['fans_id']);

            }

        }

        return $this->success($data);

    }


}